package com.ff.discounts.util

import android.graphics.BitmapFactory
import android.text.TextUtils
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.ff.discounts.AppContext
import com.ff.discounts.BuildConfig
import com.ff.discounts.R
import com.ff.discounts.superui.util.DensityUtil
import java.io.FileInputStream
import java.io.InputStream

/**
 *图片工具类
 * @author: fufang
 * @date: 2023/10/17
 */
object ImageUtil {
    /**
     * 显示本地图片
     *
     * @param view
     * @param data
     */
    fun showLocalImage(view: ImageView, data: String) {
        //获取通用配置
        val options: RequestOptions = getCommonRequestOptions()

        //使用Glide显示图片
        Glide.with(view.context)
            .load(data)
            .apply(options)
            .into(view!!)
    }




    /**
     * 获取公共配置
     *
     * @return
     */
    private fun getCommonRequestOptions(round: Boolean = false): RequestOptions {
        //创建配置选项
        val options = RequestOptions()

        //占位图
//        options.placeholder(R.drawable.placeholder)

        //出错后显示的图片
        //包括：图片不存在等情况
        options.error(R.drawable.placeholder_error)

        //从中心裁剪
//        options.centerCrop()

        if (round) {
            options.transform(RoundedCorners(DensityUtil.dip2px(com.ff.discounts.AppContext.instance, 5F).toInt()))
        }

        options.diskCacheStrategy(DiskCacheStrategy.ALL)
        return options
    }

    /**
     * 显示绝对路径图片
     *
     * @param context
     * @param view
     * @param data
     */
    fun showFull(view: ImageView, data: String) {
        //获取功能配置
        val options: RequestOptions = getCommonRequestOptions()

        //显示图片
        Glide.with(view)
            .load(data)
            .apply(options)
            .into(view!!)
    }

    /**
     * 获取图片宽高
     */
    fun getImageSize(data: String): IntArray {
        val size = IntArray(2)

        val `is`: InputStream = FileInputStream(data)

        val onlyBoundsOptions = BitmapFactory.Options()
        onlyBoundsOptions.inJustDecodeBounds = true

        BitmapFactory.decodeStream(`is`, null, onlyBoundsOptions)

        val originalWidth = onlyBoundsOptions.outWidth
        val originalHeight = onlyBoundsOptions.outHeight
        size[0] = originalWidth
        size[1] = originalHeight

        return size
    }
}